package com.beyondsoft.sabg.edu.service.dataanalysis.impl;

import com.aliyun.dataanalysisgbi20240823.models.*;
import com.aliyun.teautil.models.RuntimeOptions;
import com.beyondsoft.sabg.edu.config.AnalysisConfig;
import com.beyondsoft.sabg.edu.model.dto.SynonymDto;
import com.beyondsoft.sabg.edu.service.dataanalysis.SynonymService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 同义词服务实现类
 */
@Service
@Slf4j
public class SynonymServiceImpl implements SynonymService {

    @Autowired
    private com.aliyun.dataanalysisgbi20240823.Client analysisClient;

    @Autowired
    private AnalysisConfig analysisConfig;

    @Override
    public String createSynonym(SynonymDto synonymDto) throws Exception {
        log.info("创建同义词，主词：{}", synonymDto.getWord());

        try {
            CreateSynonymsRequest request = new CreateSynonymsRequest()
                    .setWord(synonymDto.getWord())
                    .setWordSynonyms(synonymDto.getWordSynonyms())
                    .setColumns(synonymDto.getColumns())
                    .setWorkspaceId(analysisConfig.getWorkspaceId());

            RuntimeOptions runtime = new RuntimeOptions();
            Map<String, String> headers = new HashMap<>();

            CreateSynonymsResponse response = analysisClient
                    .createSynonymsWithOptions(request, headers, runtime);

            log.info("同义词创建完成，请求ID：{}", response.getBody().getRequestId());

            if (response.getBody().getData() != null) {
                Boolean success = (Boolean) response.getBody().getData();
                if (Boolean.TRUE.equals(success)) {
                    return "同义词创建成功，请求ID：" + response.getBody().getRequestId();
                } else {
                    String errorMsg = response.getBody().getErrorMsg();
                    if (errorMsg != null && errorMsg.contains("同义词请勿重复")) {
                        throw new RuntimeException("同义词已存在，请勿重复创建");
                    } else {
                        throw new RuntimeException("创建同义词失败：" + (errorMsg != null ? errorMsg : "未知错误"));
                    }
                }
            } else {
                throw new RuntimeException("创建同义词失败：响应数据异常");
            }

        } catch (Exception e) {
            log.error("创建同义词失败", e);
            throw new RuntimeException("创建同义词失败：" + e.getMessage(), e);
        }
    }

    @Override
    public Object listSynonyms() throws Exception {
        log.info("获取同义词列表");

        try {
            ListSynonymsRequest request = new ListSynonymsRequest()
                    .setWorkspaceId(analysisConfig.getWorkspaceId());

            RuntimeOptions runtime = new RuntimeOptions();
            Map<String, String> headers = new HashMap<>();

            ListSynonymsResponse response = analysisClient
                    .listSynonymsWithOptions(request, headers, runtime);

            log.info("同义词列表获取完成");

            if (response.getStatusCode() == 200) {
                // 返回实际的数据而不是toString()
                return response.getBody().getData();
            } else {
                throw new RuntimeException("获取同义词列表失败：" + response.getBody().getErrorMsg());
            }

        } catch (Exception e) {
            log.error("获取同义词列表失败", e);
            throw new RuntimeException("获取同义词列表失败：" + e.getMessage(), e);
        }
    }

    @Override
    public String updateSynonym(SynonymDto synonymDto) throws Exception {
        log.info("修改同义词，ID：{}", synonymDto.getSynonymIdKey());

        try {
            UpdateSynonymsRequest request = new UpdateSynonymsRequest()
                    .setWorkspaceId(analysisConfig.getWorkspaceId())
                    .setSynonymIdKey(synonymDto.getSynonymIdKey())
                    .setWord(synonymDto.getWord())
                    .setWordSynonyms(synonymDto.getWordSynonyms())
                    .setColumns(synonymDto.getColumns());

            RuntimeOptions runtime = new RuntimeOptions();
            Map<String, String> headers = new HashMap<>();

            UpdateSynonymsResponse response = analysisClient
                    .updateSynonymsWithOptions(request, headers, runtime);

            log.info("同义词修改完成，");

            if (response.getStatusCode() == 200) {
                return "同义词修改成功" ;
            } else {
                throw new RuntimeException("修改同义词失败：" + response.getBody().getErrorMsg());
            }

        } catch (Exception e) {
            log.error("修改同义词失败", e);
            throw new RuntimeException("修改同义词失败：" + e.getMessage(), e);
        }
    }

    @Override
    public String batchDeleteSynonyms(List<String> synonymIdKeys) throws Exception {
        log.info("批量删除同义词，数量：{}", synonymIdKeys.size());

        try {
            BatchDeleteSynonymsRequest request = new BatchDeleteSynonymsRequest()
                    .setSynonymIdKeys(synonymIdKeys)
                    .setWorkspaceId(analysisConfig.getWorkspaceId());

            RuntimeOptions runtime = new RuntimeOptions();
            Map<String, String> headers = new HashMap<>();

            BatchDeleteSynonymsResponse response = analysisClient
                    .batchDeleteSynonymsWithOptions(request, headers, runtime);

            log.info("同义词批量删除完成，请求ID：{}", response.getBody().getRequestId());

            if (response.getStatusCode() == 200) {
                return "同义词批量删除成功，请求ID：" + response.getBody().getRequestId();
            } else {
                throw new RuntimeException("批量删除同义词失败：" + response.getBody().getErrorMsg());
            }

        } catch (Exception e) {
            log.error("批量删除同义词失败", e);
            throw new RuntimeException("批量删除同义词失败：" + e.getMessage(), e);
        }
    }
} 